package variableHeader

import (
	"gitee.com/squbirreland/imgo/mqtt/agreement/constantHeader"
	"gitee.com/squbirreland/imgo/mqtt/constant"
	"gitee.com/squbirreland/imgo/utils/byteMath"
)

// Publish VariableHeaderPublish 发布消息可变头
type Publish struct {
	//TopicName 主题名 其格式为 byte byte | 主题名
	// 前两个byte byte 指定了主题名的长度
	TopicName string
	//Identifier 报文标识符 2byte
	//只有当QoS等级是1或2时 报文标识符字段才能出现在PUBLISH报文中
	Identifier PacketIdentifier
	//
	headerLength int
	headerBytes  []byte
}

func (p *Publish) Parse(cHeader constantHeader.ConstantHeader) error {
	//解析出主题名
	topicLength := p.headerBytes[:2]
	topicLengthInt, err := byteMath.ByteArr2Int(topicLength)
	if err != nil {
		return err
	}
	p.headerLength = 2 + topicLengthInt
	topic := p.headerBytes[2:p.headerLength]
	p.TopicName = string(topic)
	//解析出identifier
	if cHeader.Zone.QOS != constant.OnlySendOnce {
		p.headerLength += 2
		identifier := p.headerBytes[p.headerLength:2]
		identifierInt, err := byteMath.ByteArr2Int(identifier)
		if err != nil {
			return err
		}
		p.Identifier = PacketIdentifier(identifierInt)
	}
	return nil
}

func (p *Publish) CreateBytes(cHeader constantHeader.ConstantHeader) error {
	return nil
}

func (p *Publish) GetLength() int {
	return p.headerLength
}

func (p *Publish) GetHeaderBytes() []byte {
	return p.headerBytes
}

func (p *Publish) SetLength(i int) {
	p.headerLength = i
}

func (p *Publish) SetHeaderBytes(b []byte) {
	p.headerBytes = b
}
